package controllers

import (
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"mishop/entitys"
	"mishop/models"
	"mishop/services"
	"mishop/utils"
	"strconv"
)

type IUser interface {
	Show(ctx *gin.Context)
	Store(ctx *gin.Context)
	Update(ctx *gin.Context)
}

// @BasePath /user/

// Store 注册用户 godoc
// @Summary ping example
// @Schemes
// @Description do ping
// @Tags example
// @Accept json
// @Produce json
// @Success 200 {string} Helloworld
// @Router / [post]
func (c *User) Store(ctx *gin.Context) {
	userStoreEntity := entitys.UserStoreEntity{}

	err := ctx.ShouldBindWith(&userStoreEntity, binding.JSON)
	utils.HandleErrors(err, ctx, 400, 1, "")

	user, err := c.service.Register(userStoreEntity)
	utils.HandleErrors(err, ctx, 400, 1, "")
	if ctx.IsAborted() {
		return
	}
	//return
	utils.HandleSucess(ctx, 201, 0, "", user)
}

// Update 更新资料
func (c *User) Update(ctx *gin.Context) {

}

func (c *User) Show(ctx *gin.Context) {
	user_id := ctx.Param("user_id")
	userID, err := strconv.Atoi(user_id)
	utils.HandleErrors(err, ctx, 400, 1, "")
	if err != nil {
		return
	}

	user, err := c.service.FindByID(uint(userID))
	utils.HandleErrors(err, ctx, 400, 1, "")
	if err != nil {
		return
	}
	utils.HandleSucess(ctx, 200, 0, "", user)
}

type User struct {
	service services.IUserService
}

func (c *User) FindByID(ctx *gin.Context) {
	product_id := ctx.Param("product_id")
	productID, err := strconv.Atoi(product_id)
	utils.HandleErrors(err , ctx , 400 , 1,"")
	if err != nil {
		return
	}
	
	product, err := c.service.FindByID(uint(productID))
	utils.HandleErrors(err , ctx , 400 , 1,"")
	if err != nil {
		return
	}

	utils.HandleSucess(ctx ,200 , 0,"",product)
}

func NewUser() IUser {
	service := services.NewUserService(models.NewUser(models.Db))
	return &User{service: service}
}
